<template>
    <el-drawer :model-value.sync="show" title="楼盘图" size="80%" direction="rtl" custom-class="drawer-building"
        :before-close="handleClose" :close-on-click-modal="false" :close-on-press-escape="false">
        <div class="drawer-building-content">
            <el-form class="search-form" label-position="top" inline>
                <el-form-item label="区域">
                    <el-cascader v-model="areaArr" placeholder="请选择" :options="areaList" :props="areaCascaderProps"
                        filterable @change="onAreaChange">
                        <template #empty>
                            <span>未搜索到相关数据</span>
                        </template>
                    </el-cascader>
                </el-form-item>
                <el-form-item label="楼盘名称">
                    <house-search :is-common="false" :project-name="buildingSelected.name" :area="areaArr"
                        :audit-status="auditStatus" @onSelect="onSelectBuilding" @createHouse="switchCreateBuildingDrawer">
                    </house-search>
                </el-form-item>
            </el-form>

            <el-tabs v-model="mediaPositionActive" size="small" @tab-click="switchMediaPositionTab">
                <el-tab-pane label="电梯内" :name="1">
                    <building-tree-elevator-inside v-if="buildingSelected.id" :loading="buildingTreeLoading"
                        :data="buildingTreeData" @onDataChange="updateBuildingOrgTreeData">
                    </building-tree-elevator-inside>
                    <span v-else class="no-data-tips">没有数据，请先搜索楼盘名称</span>
                </el-tab-pane>
                <el-tab-pane label="电梯外" :name="2">
                    <building-tree-elevator-outside v-if="buildingSelected.id" :loading="buildingTreeLoading"
                        :data="buildingTreeData" @onDataChange="updateBuildingOrgTreeData">
                    </building-tree-elevator-outside>
                    <span v-else class="no-data-tips">没有数据，请先搜索楼盘名称</span>
                </el-tab-pane>
                <el-tab-pane label="出入门" :name="3">
                    <building-tree-access-door v-if="buildingSelected.id" :loading="buildingTreeLoading"
                        :data="buildingTreeData" @onDataChange="updateBuildingOrgTreeData">
                    </building-tree-access-door>
                    <span v-else class="no-data-tips">没有数据，请先搜索楼盘名称</span>
                </el-tab-pane>
            </el-tabs>

            <Premises type="CREAT" :is-drawer-show="createBuildingDrawerShow"
                @onDrawerShow="createBuildingDrawerShow = false">
            </Premises>
        </div>
    </el-drawer>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, ref, reactive, toRefs, watch, onBeforeMount } from 'vue';
import HouseSearch from '@/components/HouseSearch.vue';
import BuildingTreeElevatorInside from '../buildingTree/BuildingTreeElevatorInside.vue';
import BuildingTreeElevatorOutside from '../buildingTree/BuildingTreeElevatorOutside.vue';
import BuildingTreeAccessDoor from '../buildingTree/BuildingTreeAccessDoor.vue';
import Premises from '@/views/resource/houseManage/components/Premises.vue';
import commonApi from '@/api/common';
import resourceApi from '@/api/resource';
import { DrawerBuildingState } from './type';

const props = defineProps({
    show: {
        type: Boolean,
        default: false,
    },
    defaultData: {
        type: Object,
        default: () => {
            return {
                areaArr: [],
                buildingId: '',
                buildingName: '',
                mediaPosition: 1,
            };
        },
    },
    auditStatus: {
        type: Array,
        default: () => null,
    },
});
const emit = defineEmits(['onDataChange']);

const state = reactive<DrawerBuildingState>({
    buildingTreeData: {
        id: '',
        pid: '',
        level: 1,
        name: '',
        premisesId: '',
        buildId: '',
        signType: 1, // signType-签约类型: 1.梯内屏，2.梯外屏，3.梯内框，4.梯外框，5.门禁，6.道闸
        eleNum: '',
        eleType: '',
        gateType: '',
        subType: '',
        showEdit: false,
        showDelete: false,
        sonList: [],
        expand: true,
    },
    buildingLoading: false,
    areaList: [],
    areaArr: [],
    areaSelected: {
        province: 0,
        city: 0,
        area: 0,
    },
    buildingSelected: {
        id: '',
        name: '',
    },
    createBuildingDrawerShow: false,
    mediaPositionActive: 1, // mediaPosition-媒体位置：1.梯内，2.梯外，3.出入门
    buildingTreeLoading: false,
});
const {
    buildingTreeData,
    buildingLoading,
    areaList,
    areaArr,
    areaSelected,
    buildingSelected,
    createBuildingDrawerShow,
    mediaPositionActive,
    buildingTreeLoading,
} = toRefs(state);
const areaCascaderProps = ref({
    label: 'name',
    value: 'id',
    children: 'childList',
});

// 获取行政区域列表
const loadRegionCodes = async () => {
    const res = await commonApi.loadRegionCodes();
    state.areaList = res;
};
onBeforeMount(() => {
    loadRegionCodes();
});
watch(
    () => props.defaultData,
    () => {
        state.areaArr = props.defaultData.areaArr || [];
        state.buildingSelected.id = props.defaultData.buildingId || '';
        state.buildingSelected.name = props.defaultData.buildingName || '';
        state.mediaPositionActive = props.defaultData.mediaPosition || 1;
        if (state.buildingSelected.id) {
            getBuildingOrgTreeData();
        }
    }
);
const onAreaChange = (areaArr: any) => {
    if (!areaArr) {
        return;
    }
    state.areaSelected.province = areaArr[0];
    state.areaSelected.city = areaArr[1];
    state.areaSelected.area = areaArr[2];
    state.buildingSelected.id = '';
    state.buildingSelected.name = '';
};

// 获取楼盘图数据
const getBuildingOrgTreeData = async () => {
    state.buildingTreeLoading = true;
    try {
        const params = {
            mediaPosition: state.mediaPositionActive,
            premisesId: state.buildingSelected.id,
        };
        const res = await resourceApi.getBuildingOrgTreeData(params);
        setElevatorName(res.sonList);
        state.buildingTreeData = JSON.parse(JSON.stringify(res));
    } finally {
        state.buildingTreeLoading = false;
    }
};

const setElevatorName = (slist: any) => {
    const sonlist = slist;
    if (!sonlist) return;
    sonlist.forEach((son: any) => {
        if (son.level === 4) {
            if (son.name) {
                son.name = son.eleNum + `(${son.name})`;
            } else {
                son.name = son.eleNum;
            }
        }
        if (son.sonList) {
            setElevatorName(son.sonList)
        }
    })
}
// 更新楼盘图数据
const updateBuildingOrgTreeData = () => {
    getBuildingOrgTreeData();
    // 楼盘图数据更新时，可通过"onDataChange"更新页面列表数据
    emit('onDataChange');
};
const onSelectBuilding = (params: any) => {
    state.buildingSelected.id = params.premiseId;
    state.buildingSelected.name = params.name;
};
watch(
    () => state.buildingSelected.id,
    () => {
        if (state.buildingSelected.id) {
            getBuildingOrgTreeData();
        }
    }
);
// 开关创建楼盘Drawer
const switchCreateBuildingDrawer = () => {
    state.createBuildingDrawerShow = !state.createBuildingDrawerShow;
};
// 切换媒体位置Tab
const switchMediaPositionTab = (tab: { paneName: number }) => {
    if (!state.buildingSelected.id) {
        return;
    }
    state.mediaPositionActive = tab.paneName;
    getBuildingOrgTreeData();
};

// 关闭楼盘图Drawer
const handleClose = () => {
    emit('update:show', !props.show);
};
</script>

<style lang="scss" scoped>
.drawer-building {}

.drawer-building-content {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.search-form {
    .el-form-item {
        width: calc((100% - 16px) / 2);
        margin-right: 0;

        & + .el-form-item {
            margin-left: 16px;
        }
    }
}

.no-data-tips {
    width: 100%;
    font-size: 14px;
    color: #000;
    text-align: center;
    margin-top: 188px;
    display: inline-block;
}

.zm-tree-org {
    padding: 0;
}

::v-deep {
    .el-dialog {
        background: #fff;
        box-shadow: 0 0 4px 1px rgba(0, 0, 0, 0.1), 0 4px 6px 1px rgba(0, 0, 0, 0.05);
        border-radius: 4px 4px 4px 4px;

        .el-dialog__header {
            padding: 20px 20px 0;

            .el-dialog__title {
                font-size: 16px;
                font-weight: bold;
                color: #252525;
            }
        }

        .el-dialog__body {
            padding: 20px 20px 0;
        }

        .el-dialog__footer {
            padding: 12px 20px 20px;

            .el-button {
                font-size: 15px;
                color: #333;
                line-height: 24px;
                border-radius: 4px 4px 4px 4px;
                padding: 12px 24px;
            }

            .el-button--default {
                border: 1px solid #e0e0e0;
            }

            .el-button--primary {
                color: #fcfcfc;
                border: none;
                background: #e60044;
            }
        }

        .el-form {
            .el-form-item {

                .el-input,
                .el-select {
                    width: 260px;
                }

                .el-input__inner {
                    width: 100%;
                }
            }
        }
    }

    .el-tabs {
        display: flex;
        flex-direction: column;
        flex: 1;

        .el-tabs__header {}

        .el-tabs__content {
            flex: 1;
            display: flex;
            flex-direction: column;

            .el-tab-pane {
                flex: 1;
            }
        }
    }
}
</style>
